class LoopQueue {
  constructor (capacity) {
    this._items = new Array(capacity + 1) // 数据实际长度为容量+1, 循环队列会浪费一个空间来区分队满和队空
    this._front = 0
    this._tail = 0
    this._size = 0
  }

  isFull () {
    return (this._tail + 1) % this._items.length === this._front
  }

  isEmpty () {
    return this._tail === this._front
  }

  getSize () {
    return this._size
  }

  enqueue (elem) {
    if (this.isFull()) {
      throw new Error('queue is full')
    }
    this._items[this._tail] = elem
    this._tail = (this._tail + 1) % this._items.length
    this._size++
  }

  dequeue () {
    if (this.isEmpty()) {
      throw new Error('queue is empty')
    }
    const result = this._items[this._front]
    this._front = (this._front + 1) % this._items.length
    this._size--
    return result
  }

  peek () {
    return this.isEmpty() ? undefined : this._items[this._front]
  }
}

export default LoopQueue
